package uia.alumni.useradm;

import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.http.HttpServletRequest;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Page;



/**
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class EditUserRoles extends Page implements Constants {

    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "admin.edituserroles";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    public EditUserRoles() {
        super(Role.admin);
    }


    /**
     * Write a form for changing a user's roles. The user is specified
     * by the parameter UID.
     * @param out
     * @param request
     */
    public void writeBody(PrintWriter out, HttpServletRequest request) {
        long uid = parseLong(request.getParameter(UID), -1);

        EntityManager em = emf.createEntityManager();
        User u = em.find(User.class, uid);

        if (u != null) {
            out.println("<h1>Edit roles of "+u.getUserName()+"</h1>");

            printStartForm(out, SaveUserRoles.SERVLET_NAME);
            //out.println("<form action=\"test.info\" method=\"post\">");
            out.println("<input type=\"hidden\" name=\""
                    +UID+"\" value=\""+uid+"\"/>");
            out.println("<table>");
            for (Role r : Role.values()) {
                String rn = r.name();
                this.printCheckBox(out, rn, rn, u.hasRole(r));
            }
            out.println("</table>");
            out.println("<input type=\"submit\" value=\"Save Roles\"/>");
            out.println("</form>");
        }
        else {
            out.println("<h1>Edit roles of nobody?</h1>");
        }

        printStartForm(out, UserAdmin.SERVLET_NAME);
        out.println("<input type=\"submit\" value=\"Cancel\"/>");
        out.println("</form>");
    }


    public final static long serialVersionUID = 1;
}
